<script setup>
import {ref, watch, onMounted, computed, nextTick} from 'vue';
import formFunc from './form-func.vue';
import {isApp, isFuncModule, hasFuncModuleEdit, isPlatform, isGlobal} from './common.js';
import _ from 'lodash';
import {useCommonStore} from "@jzl/stores";
import {api} from "@jzl/api";
import {DFT_ICONS} from "@jzl/icons";
import {openCompInWin} from "@jzl/comps";

const props = defineProps({
  currentData: Object
});

const loading = ref(false);
const funcData = ref(null);
const datasTableHeight = ref(500);
const funcs = ref([]);
const appId = ref(null);
const type = ref(4);
const form = ref(null);
const formFuncWinName = ref('');
const formFuncWinShow = ref(false);
const formFuncScriptWinShow = ref(false);
const datasContainer = ref(null);

const moduleFilePath = computed(() => {
  let moduleCode = _.get(props.currentData, "func_module_code") || "";
  let type = _.get(props.currentData, "type");
  let appCode = _.get(props.currentData, "app.group_code") || "";
  let projectCode = _.get(project.value, "project_domain");
  let prefix = "";

  if (!moduleCode) return "";

  if (type === 1) {
    prefix = "/_func/";
  } else if (type === 2) {
    prefix = `/${projectCode}/_func/`;
  } else {
    prefix = `/${projectCode}/${appCode}/func/`;
  }

  return `低码文件：${prefix}${moduleCode}.js`;
});

const loginUser = computed(() => useCommonStore().loginUser);
const project = computed(() => useCommonStore().project);

const init = async () => {
  await loadFuncs();
  handleResize();
};

const moduleNameLabel = (data) => {
  return _.get(data, "module.func_module_name");
}

const handleResize = () => {
  nextTick(() => {
    if (!datasContainer.value) return;

    let rect = datasContainer.value.getBoundingClientRect();
    let height = _.get(rect, 'height');
    if (height > 0) {
      datasTableHeight.value = height;
    }
  });
};

const loadFuncs = async () => {
  funcs.value = [];

  if (!props.currentData) return;

  if (props.currentData.datas) {
    funcs.value = props.currentData.datas;
    return;
  }

  loading.value = true;

  let appIdValue = _.get(props.currentData, 'id');
  let funcsData = [];
  let typeValue = 2;
  let funcModuleId = _.get(props.currentData, "func_module_id");

  if (funcModuleId && funcModuleId > 0) {
    typeValue = _.get(props.currentData, "type");
  } else {
    if (isPlatform(props.currentData)) {
      typeValue = 1;
    } else if (isGlobal(props.currentData)) {
      typeValue = 2;
    } else if (isApp(props.currentData)) {
      typeValue = 3;
    }
  }

  funcsData = await api.func.getFuncs({type: typeValue, app_id: appIdValue, func_module_id: funcModuleId});

  if (appIdValue > 0) {
    appId.value = appIdValue;
  } else {
    appId.value = -1;
  }

  type.value = typeValue;
  funcs.value = funcsData;
  loading.value = false;
};

const getFuncStorePath = (data) => {
  let moduleCode = _.get(data, "module.func_module_code") || "";
  let type = _.get(data, "type") || _.get(data, "module.type");
  let appCode = _.get(data, "app.group_code") || _.get(data, "module.app.group_code") || "";
  let projectCode = _.get(project.value, "project_domain");
  let prefix = "";

  if (!moduleCode) return "所属模块不正确！";

  if (type === 1) {
    prefix = "/_func/";
  } else if (type === 2) {
    prefix = `/${projectCode}/_func/`
  } else {
    prefix = `/${projectCode}/${appCode}/func/`;
  }

  // console.log(`---------->>> getFuncStorePath: `, data)
  return `${prefix}${moduleCode}.js`;
}

const openCreateEditWin = () => {
  openCompInWin(formFunc, {
    funcData: funcData.value,
    module:  props.currentData,
    onCancel: async (isUpdate, x1, x2) => {
      // formFuncWinShow.value = false;
      console.log(isUpdate, x1, x2)
      if (isUpdate) {
        props.currentData.datas = null;
        await init();
      }
    }
  }, {
    title: formFuncWinName.value,
    width: 600,
    showConfirmButton: false,
    showCancelButton: false
  })
}

const handleShowCreateFunc = () => {
  let name = _.get(props.currentData, 'func_module_name');

  funcData.value = null;
  formFuncWinName.value = `【${name}】下新增函数`;
  // formFuncWinShow.value = true;

  openCreateEditWin();
};

/*const handleFuncWinClose = async (isUpdate) => {
  formFuncWinShow.value = false;

  if (isUpdate) {
    props.currentData.datas = null;
    await init();
  }
};*/

const handleOptionEdit = (option) => {
  let name = _.get(option, 'func_name');

  funcData.value = option;
  formFuncWinName.value = `【${name}】函数修改`;
  // formFuncWinShow.value = true;
  openCreateEditWin()
};

const handleOptionRemove = (option) => {
  let dt = option;

  if (!dt || !dt.func_id) return;

  let msg = `确定删除【${dt.func_name}】?`;
  let ret = null;

  $jui.confirm(msg).then(async () => {
    loading.value = true;

    ret = await api.func.removeFunc(dt.func_id);

    if (ret) {
      await init();
    }

    loading.value = false;
  }).catch(e => {
    console.error(e)
  });
};

const handleFuncScriptWinShow = (data) => {
  form.value = data;
  formFuncScriptWinShow.value = true;
};

const handleSave = async () => {
  let formValue = _.cloneDeep(form.value);
  let tip = '';

  if (!formValue) return;
  loading.value = true;

  let funcId = _.get(formValue, 'func_id');
  let ret;

  if (funcId) {
    ret = await api.func.updateFunc(formValue);
  } else {
    ret = await api.func.createFunc(formValue);
  }

  if (ret) {
    formFuncScriptWinShow.value = false;
    init();
  }

  loading.value = false;
};

const handleClearCache = async () => {
  let funcModuleId = _.get(props.currentData, "func_module_id");

  if (!funcModuleId || funcModuleId <= 0) return;

  let ret = await api.func.clearCache(funcModuleId);

  if (ret) {
    $jui.toast('操作成功！');
  }
};

onMounted(() => {
  init();
});

watch(() => props.currentData.id, () => {
  handleResize();
  loadFuncs();
});

watch(() => props.currentData.func_module_id, () => {
  handleResize();
  loadFuncs();
});
</script>

<template>
  <div
    class="mb-info flex flex-col flex-1"
    v-if="currentData"
    v-loading="loading"
  >
    <div
      class="app-portal-cnt-hd"
      v-if="currentData.name"
    >
      <div class="app-portal-hd-icon">
        <JIcon :icon="DFT_ICONS.platform" v-if="currentData.id === -100" />
        <JIcon :icon="DFT_ICONS.global" v-else-if="currentData.id === -1" />
        <JIcon :icon="DFT_ICONS.app" v-else-if="isApp(currentData)" />
        <JIcon :icon="DFT_ICONS.js" v-else-if="isFuncModule(currentData)" />
      </div>
      <div class="app-portal-title" v-html="currentData.name"></div>
      <div class="app-portal-mark" v-copy="currentData.func_module_code"
           v-tippy="{ arrow: true, placement: 'right' }" content="点击复制">{{ currentData.func_module_code }}
      </div>
      <div class="api-file-path">{{ moduleFilePath }}</div>
      <el-button
        class="app-group-add-btn"
        type="text"
        size="small"
        @click="handleClearCache">
        <template #icon>
          <JIcon :icon="DFT_ICONS.refresh"/>
        </template>
        刷新缓存
      </el-button>
      <el-button
        class="app-group-add-btn"
        type="text"
        size="small"
        v-if="isFuncModule(currentData)"
        @click="handleShowCreateFunc()">
        <template #icon>
          <JIcon :icon="DFT_ICONS.add"/>
        </template>
        注册函数
      </el-button>
    </div>
    <div class="app-portal-cnt-bd" ref="datasContainer">
      <el-table
        :data="funcs"
        size="small"
        row-key="mb_id"
        :tree-props="{ children: 'subs' }"
        :height="datasTableHeight"
        class="m-table"
        indent="0"
        default-expand-all
      >
        <el-table-column prop="func_code" label="函数方法名">
          <template #default="scope">
            <div
              class="text-copy-wrap font-bold"
              :class="{ 'empty': !scope.row.func_code }"
              style="font-size:13px;"
              v-copy="scope.row.func_code"
              v-tippy="{ arrow: true, placement: 'right' }" content="点击复制"
            >
              {{ scope.row.func_code }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="func_name" label="函数中文名">
          <template #default="scope">
            <div
              v-tippy="{ arrow: true, placement: 'top-start' }"
              :content="scope.row.func_remark || scope.row.func_name"
            >{{ scope.row.func_name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="func_module_name" label="所属函数包" width="160">
          <template #default="scope">
            <el-tag>{{ moduleNameLabel(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="代码">
          <template #default="scope">
            <template v-if="scope.row.script_store === 1">
              <el-button type="text" size="small">
                <template #icon>
                  <JIcon :icon="DFT_ICONS.fileLocal"/>
                </template>
                <span style="color: #999;">代码地址：{{ getFuncStorePath(scope.row) }}</span>
              </el-button>
            </template>
            <template v-else>
              <el-button
                size="small"
                type="text"
                v-tippy="{ arrow: true }" content="新增"
                @click="handleFuncScriptWinShow(scope.row)">
                <template #icon>
                  <JIcon :icon="DFT_ICONS.pc" />
                </template> 在线开发
              </el-button>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="100"
          align="center"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              size="small"
              type="text"
              v-tippy="{ arrow: true }"
              content="修改"
              @click="handleOptionEdit(scope.row)"
            >
              <template #icon>
                <JIcon :icon="DFT_ICONS.edit" />
              </template>
            </el-button>
            <el-button
              v-if="hasFuncModuleEdit(currentData)"
              size="small"
              type="text"
              v-tippy="{ arrow: true }"
              content="删除"
              @click="handleOptionRemove(scope.row)"
            >
              <template #icon>
                <JIcon :icon="DFT_ICONS.delete" />
              </template>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

<!--    <el-dialog
      v-model="formFuncWinShow"
      :title="formFuncWinName"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-func
        v-if="formFuncWinShow"
        :func-data="funcData"
        :module="currentData"
        @close="handleFuncWinClose"
      ></form-func>
    </el-dialog>-->

    <el-drawer
      v-model="formFuncScriptWinShow"
      :title="formFuncWinName"
      :append-to-body="true"
      :with-header="false" size="96%"
      direction="rtl"
      class="wf-node-prop-drawer">
      <div class="func-form-body">
        <lownode-func v-model="form" :app-id="appId" :type="type">
          <div class="func-form-actions" slot="header-tools">
            <el-button @click="formFuncScriptWinShow = false" size="small" style="width:80px;"> 取消</el-button>
            <el-button type="primary" @click="handleSave" size="small" style="width:80px;"> 保存</el-button>
          </div>
        </lownode-func>
      </div>
    </el-drawer>

    <resize-observer @notify="handleResize"/>
  </div>
</template>

<style lang="scss" scoped>
.text-copy-wrap {
  position: relative;

  &.empty {
    color: #CCC;
  }

  .el-button {
    display: none;
    position: absolute;
    right: 0px;
    top: 50%;
    transform: translateY(-50%);
    background: #FFF;
    padding-left: 5px;
    padding-right: 5px;
  }

  &:hover {
    .el-button {
      display: block;
    }
  }
}

.api-file-path {
  flex: 1;
  font-weight: bold;
  text-align: center;
}
</style>
